package com.yydlz.gift.controller;

import com.yydlz.gift.entity.Gift;
import com.yydlz.gift.entity.GiftAndPhoto;
import com.yydlz.gift.service.GiftService;
import io.lettuce.core.dynamic.annotation.Value;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Gift)表控制层
 *
 * @author makejava
 * @since 2021-12-15 12:38:30
 */
@RestController
@RequestMapping("giftapi")
@Api(tags = "礼物模块",description = "礼物相关模块接口")
public class GiftController {
    /**
     * 服务对象
     */
    @Resource
    private GiftService giftService;


    /**
     * 分页查询
     *
     * @param map
     * @return 查询结果
     */
    @PostMapping("/queryByLimit")
    @ApiOperation(value = "获取某一页的礼物列表")
//    public List<Gift> queryByLimit(/*Gift gift,*//*@ApiParam(name="pageNum",value="页码，从0开始",required = true)*/ @RequestParam("pageNum") int pageNum, /*@ApiParam("pageSize")*/ @RequestParam("pageSize") int pageSize) {
    public List<Gift> queryByLimit(@RequestBody Map<String,Integer> map) {
        int pageNum = map.get("pageNum");
        int pageSize = map.get("pageSize");
        return this.giftService.queryByPage(/*gift*/ pageNum,pageSize);
    }

    /**
     * 获取礼物个数
     * @return
     */
    @GetMapping("getGiftNum")
    public int getGiftNum(){
        Gift gift = new Gift();
        return (int) this.giftService.count(gift);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param map
     * @return 单条数据
     */
    @PostMapping("/queryById")
    public ResponseEntity<Gift> queryById(@RequestBody Map<String,Object> map) {
        int id =(int)map.get("id");
        return ResponseEntity.ok(this.giftService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param giftAndPhoto 实体
     * @return 新增结果
     */
//    @PostMapping("/insert")
//    public ResponseEntity<Gift> insert(@RequestBody GiftAndPhoto giftAndPhoto){
//        String uploadPathImg="/root/yydlz/node/views/photo/";
//        MultipartFile file = giftAndPhoto.getFile();
//        Gift gift = giftAndPhoto.getGift();
//
//        try {
//            if (file != null) {
//                String fileName = System.currentTimeMillis() + file.getOriginalFilename();
//                String upload_file_dir=uploadPathImg;//注意这里需要添加目录信息
//                String destFileName =  "./photo/" +fileName;
//                //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）
//                File upload_file_dir_file = new File(upload_file_dir);
//                if (!upload_file_dir_file.exists())
//                {
//                    upload_file_dir_file.mkdirs();
//                }
//                //5.把浏览器上传的文件复制到希望的位置
//                File targetFile = new File(upload_file_dir_file, fileName);
//                file.transferTo(targetFile);
//                gift.setImg(destFileName);
//            }
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//        return ResponseEntity.ok(this.giftService.insert(gift));
//    }


    /**
     * 新增数据
     *
     * @param giftAndPhoto 实体
     * @return 新增结果
     */
    @PostMapping("/add")
    public Map<String,Object> add(@RequestBody GiftAndPhoto giftAndPhoto){
        Map<String,Object> map = new HashMap<>();


        //分解出相应的量，并转换
        String base64Data = giftAndPhoto.getBase64Photo();
        String startTime = giftAndPhoto.getStartTime();
        String endTime = giftAndPhoto.getEndTime();
        Gift gift = giftAndPhoto.getGift();

        //时间string→Date
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos1 = new ParsePosition(0);
        ParsePosition pos2 = new ParsePosition(0);
        if(startTime!=null)
            gift.setStartTime(formatter.parse(startTime, pos1));
        if(endTime!=null)
            gift.setEndTime(formatter.parse(endTime, pos2));

        // 设置必填字段
        if(startTime==null || endTime==null || gift.getInfo()==null || gift.getName()==null || gift.getNum()==null){
            map.put("state", false);
            map.put("msg", "必填信息有空缺！");
            return map;
        }


        map.put("state", true);
        map.put("msg", "添加成功");

        if(gift.getImg()==null || gift.getImg().equals("")){
            gift.setImg("./photo/default.png");
            map.put("gift",this.giftService.insert(gift));
            return map;
        }

        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据
        if(base64Data==null||"".equals(base64Data)){
            gift.setImg("./photo/default.png");
            map.put("gift",this.giftService.insert(gift));
            return map;
        }else {
            String [] d = base64Data.split("base64,");//将字符串分成数组
            if(d != null && d.length == 2){
                dataPrix = d[0];
                data = d[1];
            }else {
                gift.setImg("./photo/default.png");
                map.put("gift",this.giftService.insert(gift));
                return map;
            }
        }
        String suffix = "";//图片后缀，用以识别哪种格式数据
        //编码的jpeg图片数据
        if("data:image/jpeg;".equalsIgnoreCase(dataPrix) || "data:image/jpg;".equalsIgnoreCase(dataPrix)){
            suffix = ".jpg";
        }else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){
            //编码的icon图片数据
            suffix = ".ico";
        }else if("data:image/gif;".equalsIgnoreCase(dataPrix)){
            //编码的gif图片数据
            suffix = ".gif";
        }else if("data:image/png;".equalsIgnoreCase(dataPrix)){
            //编码的png图片数据
            suffix = ".png";
        }else {
            gift.setImg("./photo/default.png");
            map.put("gift",this.giftService.insert(gift));
            return map;
        }
        String uploadPathImg="/root/yydlz/node/views/photo/";
//        String uploadPathImg="D:\\Images\\";
        String fileName = System.currentTimeMillis()+suffix;
        String upload_file_dir=uploadPathImg+fileName;//注意这里需要添加目录信息
        String destFileName =  "./photo/" +fileName;

        File upload_file_dir_file = new File(uploadPathImg);
        if (!upload_file_dir_file.exists())
        {
            upload_file_dir_file.mkdirs();
        }

        try {
            //Base64解码
            byte[] b = Base64Utils.decodeFromString(data);
            for(int i=0;i<b.length;++i) {
                if(b[i]<0) {
                    //调整异常数据
                    b[i]+=256;
                }
            }
            OutputStream out = new FileOutputStream(upload_file_dir);
            out.write(b);
            out.flush();
            out.close();
            gift.setImg(destFileName);
        } catch (IOException e) {
            e.printStackTrace();
            gift.setImg("./photo/default.png");
        }

        map.put("gift",this.giftService.insert(gift));
        return map;
    }

    /**
     * 编辑数据
     *
     * @param giftAndPhoto 实体
     * @return 编辑结果
     */
    @PostMapping("/edit")
    public ResponseEntity<Gift> edit(@RequestBody GiftAndPhoto giftAndPhoto) {
        //分解出相应的量，并转换
        String base64Data = giftAndPhoto.getBase64Photo();
        String startTime = giftAndPhoto.getStartTime();
        String endTime = giftAndPhoto.getEndTime();
        Gift gift = giftAndPhoto.getGift();

        //时间string→Date
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos1 = new ParsePosition(0);
        ParsePosition pos2 = new ParsePosition(0);
        if(startTime!=null)
            gift.setStartTime(formatter.parse(startTime, pos1));
        if(endTime!=null)
            gift.setEndTime(formatter.parse(endTime, pos2));

        //不传图片则不更新图片
        if(base64Data == null){
            return ResponseEntity.ok(this.giftService.update(gift));
        }


        //处理图片
        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据
        if("".equals(base64Data)){
            gift.setImg("./photo/default.png");
            return ResponseEntity.ok(this.giftService.update(gift));
        }else {
            String [] d = base64Data.split("base64,");//将字符串分成数组
            if(d != null && d.length == 2){
                dataPrix = d[0];
                data = d[1];
            }else {
                gift.setImg("./photo/default.png");
                return ResponseEntity.ok(this.giftService.update(gift));
            }
        }
        String suffix = "";//图片后缀，用以识别哪种格式数据
        //编码的jpeg图片数据
        if("data:image/jpeg;".equalsIgnoreCase(dataPrix) || "data:image/jpg;".equalsIgnoreCase(dataPrix)){
            suffix = ".jpg";
        }else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){
            //编码的icon图片数据
            suffix = ".ico";
        }else if("data:image/gif;".equalsIgnoreCase(dataPrix)){
            //编码的gif图片数据
            suffix = ".gif";
        }else if("data:image/png;".equalsIgnoreCase(dataPrix)){
            //编码的png图片数据
            suffix = ".png";
        }else {
            gift.setImg("./photo/default.png");
            return ResponseEntity.ok(this.giftService.update(gift));
        }
        String uploadPathImg="/root/yydlz/node/views/photo/";
//        String uploadPathImg="D:\\Images\\";
        String fileName = System.currentTimeMillis()+suffix;
        String upload_file_dir=uploadPathImg+fileName;//注意这里需要添加目录信息
        String destFileName =  "./photo/" +fileName;

        File upload_file_dir_file = new File(uploadPathImg);
        if (!upload_file_dir_file.exists())
        {
            upload_file_dir_file.mkdirs();
        }

        try {
            //Base64解码
            byte[] b = Base64Utils.decodeFromString(data);
            for(int i=0;i<b.length;++i) {
                if(b[i]<0) {
                    //调整异常数据
                    b[i]+=256;
                }
            }
            OutputStream out = new FileOutputStream(upload_file_dir);
            out.write(b);
            out.flush();
            out.close();
            gift.setImg(destFileName);
        } catch (IOException e) {
            e.printStackTrace();
            gift.setImg("./photo/default.png");
            return ResponseEntity.ok(this.giftService.update(gift));
        }

        return ResponseEntity.ok(this.giftService.update(gift));
    }

    /**
     * 删除数据
     *
     * @param map
     * @return 删除是否成功
     */
    @PostMapping("/deleteById")
    public ResponseEntity<Boolean> deleteById(@RequestBody Map<String,Object> map) {
        int id =(int)map.get("id");
        return ResponseEntity.ok(this.giftService.deleteById(id));
    }

}

